<template>
  <div class="delivery-calculation-container">
    <el-card class="delivery-card">
      <template #header>
        <div class="card-header">
          <h2>交期承诺计算</h2>
          <el-button type="primary">运行交期分析</el-button>
        </div>
      </template>
      
      <div class="delivery-content">
        <div class="filters">
          <el-form :model="filterForm" label-position="top" inline>
            <el-form-item label="产品类型">
              <el-select v-model="filterForm.productType" placeholder="选择产品类型">
                <el-option label="标准产品" value="standard" />
                <el-option label="定制产品" value="custom" />
                <el-option label="预制件" value="prefab" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="生产基地">
              <el-select v-model="filterForm.productionBase" placeholder="选择生产基地">
                <el-option label="华东基地" value="east" />
                <el-option label="华南基地" value="south" />
                <el-option label="华北基地" value="north" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="优先级">
              <el-select v-model="filterForm.priority" placeholder="选择优先级">
                <el-option label="常规" value="normal" />
                <el-option label="加急" value="urgent" />
                <el-option label="特急" value="critical" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="配送方式">
              <el-select v-model="filterForm.deliveryMethod" placeholder="选择配送方式">
                <el-option label="标准物流" value="standard" />
                <el-option label="快递" value="express" />
                <el-option label="自提" value="selfPickup" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="calendar-view">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="inner-card">
                <template #header>
                  <div class="inner-header">
                    <h3>生产能力日历</h3>
                    <el-switch v-model="showCapacityOverlay" active-text="显示负载" />
                  </div>
                </template>
                
                <div class="calendar-container">
                  <div class="calendar-legend">
                    <div class="legend-item">
                      <div class="color-box normal"></div>
                      <span>正常负载</span>
                    </div>
                    <div class="legend-item">
                      <div class="color-box medium"></div>
                      <span>中等负载</span>
                    </div>
                    <div class="legend-item">
                      <div class="color-box high"></div>
                      <span>高负载</span>
                    </div>
                    <div class="legend-item">
                      <div class="color-box overload"></div>
                      <span>超负荷</span>
                    </div>
                  </div>
                  
                  <el-calendar v-model="selectedDate">
                    <template #dateCell="{ data }">
                      <div class="calendar-cell" :class="getCapacityClass(data.day)">
                        <p :class="{ 'is-selected': data.isSelected }">
                          {{ data.day.split('-').slice(2).join('') }}
                        </p>
                        <div v-if="showCapacityOverlay" class="capacity-info">
                          {{ getCapacityInfo(data.day) }}
                        </div>
                      </div>
                    </template>
                  </el-calendar>
                </div>
              </el-card>
            </el-col>
            
            <el-col :span="12">
              <el-card class="inner-card">
                <template #header>
                  <h3>交期预测</h3>
                </template>
                
                <div class="prediction-container">
                  <div class="input-section">
                    <el-form :model="orderForm" label-position="top">
                      <el-form-item label="订单数量">
                        <el-input-number v-model="orderForm.quantity" :min="1" :step="10" />
                      </el-form-item>
                      
                      <el-form-item label="预计下单日期">
                        <el-date-picker v-model="orderForm.orderDate" type="date" placeholder="选择日期" />
                      </el-form-item>
                      
                      <el-form-item label="交货地址">
                        <el-cascader
                          v-model="orderForm.deliveryAddress"
                          :options="addressOptions"
                          placeholder="请选择交货地址"
                        />
                      </el-form-item>
                      
                      <el-button type="primary" @click="calculateDeliveryDate">计算预计交期</el-button>
                    </el-form>
                  </div>
                  
                  <div v-if="showResult" class="result-section">
                    <el-divider>计算结果</el-divider>
                    
                    <el-timeline>
                      <el-timeline-item
                        v-for="(item, index) in deliveryTimeline"
                        :key="index"
                        :type="item.type"
                        :color="item.color"
                        :timestamp="item.timestamp"
                      >
                        {{ item.content }}
                      </el-timeline-item>
                    </el-timeline>
                    
                    <el-alert
                      title="承诺交期"
                      :description="`预计最早交期：${earliestDelivery}，承诺交期：${promisedDelivery}`"
                      type="success"
                      show-icon
                    />
                    
                    <el-alert
                      v-if="hasRisk"
                      style="margin-top: 10px"
                      title="交期风险提示"
                      :description="riskMessage"
                      type="warning"
                      show-icon
                    />
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
        <div class="statistics-section">
          <el-divider>历史交期统计</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="stat-header">
                  <div class="stat-title">交付及时率</div>
                  <div class="stat-value">92%</div>
                </div>
                <div class="stat-chart" ref="onTimeChart"></div>
              </el-card>
            </el-col>
            
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="stat-header">
                  <div class="stat-title">平均交期偏差</div>
                  <div class="stat-value">-0.8 天</div>
                </div>
                <div class="stat-chart" ref="deviationChart"></div>
              </el-card>
            </el-col>
            
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="stat-header">
                  <div class="stat-title">平均生产周期</div>
                  <div class="stat-value">12.5 天</div>
                </div>
                <div class="stat-chart" ref="cycleChart"></div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'

// 定义过滤表单数据
const filterForm = reactive({
  productType: '',
  productionBase: '',
  priority: '',
  deliveryMethod: ''
})

// 定义订单表单数据
const orderForm = reactive({
  quantity: 100,
  orderDate: new Date(),
  deliveryAddress: [] as string[]
})

// 日历相关
const selectedDate = ref(new Date())
const showCapacityOverlay = ref(true)

// 定义时间轴项类型
interface TimelineItem {
  content: string;
  timestamp: string;
  type: string;
  color: string;
}

// 结果相关
const showResult = ref(false)
const earliestDelivery = ref('')
const promisedDelivery = ref('')
const hasRisk = ref(false)
const riskMessage = ref('')
const deliveryTimeline = ref<TimelineItem[]>([])

// 图表引用
const onTimeChart = ref(null)
const deviationChart = ref(null)
const cycleChart = ref(null)
let onTimeChartInstance: echarts.ECharts | null = null
let deviationChartInstance: echarts.ECharts | null = null
let cycleChartInstance: echarts.ECharts | null = null

// 地址选项
const addressOptions = [
  {
    value: 'zhejiang',
    label: '浙江',
    children: [
      {
        value: 'hangzhou',
        label: '杭州',
        children: [
          { value: 'xihu', label: '西湖区' },
          { value: 'jianggan', label: '江干区' }
        ]
      },
      {
        value: 'ningbo',
        label: '宁波',
        children: [
          { value: 'jiangbei', label: '江北区' },
          { value: 'yinzhou', label: '鄞州区' }
        ]
      }
    ]
  },
  {
    value: 'jiangsu',
    label: '江苏',
    children: [
      {
        value: 'nanjing',
        label: '南京',
        children: [
          { value: 'gulou', label: '鼓楼区' },
          { value: 'jianye', label: '建邺区' }
        ]
      },
      {
        value: 'suzhou',
        label: '苏州',
        children: [
          { value: 'wuzhong', label: '吴中区' },
          { value: 'gusu', label: '姑苏区' }
        ]
      }
    ]
  }
]

// 产能负载随机数据（实际应该从API获取）
interface CapacityData {
  [key: string]: number;
}

const capacityData: CapacityData = {
  '2023-07-01': 30,
  '2023-07-02': 45,
  '2023-07-03': 70,
  '2023-07-04': 60,
  '2023-07-05': 85,
  '2023-07-06': 95,
  '2023-07-07': 50,
  '2023-07-08': 40,
  '2023-07-09': 35,
  '2023-07-10': 65,
  '2023-07-11': 75,
  '2023-07-12': 90,
  '2023-07-13': 100,
  '2023-07-14': 55
}

// 获取日期对应的产能等级样式
const getCapacityClass = (day: string) => {
  const date = day.substring(0, 10)
  const capacity = capacityData[date] || Math.floor(Math.random() * 100)
  
  if (capacity < 40) return 'normal-capacity'
  if (capacity < 70) return 'medium-capacity'
  if (capacity < 90) return 'high-capacity'
  return 'overload-capacity'
}

// 获取日期对应的产能信息
const getCapacityInfo = (day: string) => {
  const date = day.substring(0, 10)
  const capacity = capacityData[date] || Math.floor(Math.random() * 100)
  return `${capacity}%`
}

// 计算预计交期
const calculateDeliveryDate = () => {
  // 这里是示例逻辑，实际应该根据各种因素综合计算
  const orderDate = dayjs(orderForm.orderDate)
  
  // 生产所需天数（根据数量估算）
  const productionDays = Math.ceil(orderForm.quantity / 20) // 假设每天能生产20个单位
  
  // 运输所需天数（根据地址估算）
  let transportDays = 2 // 默认运输时间
  if (orderForm.deliveryAddress?.[0] === 'jiangsu') {
    transportDays = 3 // 假设江苏地区需要3天
  }
  
  // 计算最早可能的交期（不考虑产能限制）
  const earliestDate = orderDate.add(productionDays + transportDays, 'day')
  earliestDelivery.value = earliestDate.format('YYYY-MM-DD')
  
  // 考虑产能限制，可能需要延后（加入缓冲时间）
  const bufferDays = 2 // 缓冲天数
  const promisedDate = earliestDate.add(bufferDays, 'day')
  promisedDelivery.value = promisedDate.format('YYYY-MM-DD')
  
  // 判断是否存在风险
  hasRisk.value = orderForm.quantity > 200
  riskMessage.value = hasRisk.value ? 
    '当前订单数量较大，可能导致生产排期紧张，建议提前与客户沟通可能的延期风险。' : ''
  
  // 生成时间轴数据
  deliveryTimeline.value = [
    {
      content: '订单确认',
      timestamp: orderDate.format('YYYY-MM-DD'),
      type: 'primary',
      color: '#409EFF'
    },
    {
      content: '开始生产',
      timestamp: orderDate.add(2, 'day').format('YYYY-MM-DD'),
      type: 'primary',
      color: '#409EFF'
    },
    {
      content: '生产完成',
      timestamp: orderDate.add(2 + productionDays, 'day').format('YYYY-MM-DD'),
      type: 'primary',
      color: '#409EFF'
    },
    {
      content: '发货',
      timestamp: orderDate.add(3 + productionDays, 'day').format('YYYY-MM-DD'),
      type: 'primary',
      color: '#409EFF'
    },
    {
      content: '预计送达',
      timestamp: promisedDelivery.value,
      type: 'success',
      color: '#67C23A'
    }
  ]
  
  showResult.value = true
}

// 初始化准时率图表
const initOnTimeChart = () => {
  if (!onTimeChart.value) return
  
  onTimeChartInstance = echarts.init(onTimeChart.value)
  
  const option = {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 10,
        axisLine: {
          lineStyle: {
            width: 6,
            color: [
              [0.7, '#F56C6C'],
              [0.9, '#E6A23C'],
              [1, '#67C23A']
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '12%',
          width: 20,
          offsetCenter: [0, '-60%'],
          itemStyle: {
            color: 'inherit'
          }
        },
        axisTick: {
          length: 12,
          lineStyle: {
            color: 'auto',
            width: 2
          }
        },
        splitLine: {
          length: 20,
          lineStyle: {
            color: 'auto',
            width: 5
          }
        },
        axisLabel: {
          color: '#999',
          fontSize: 12,
          distance: -60,
          formatter: function(value: number) {
            if (value === 100) {
              return '100%'
            }
            return ''
          }
        },
        title: {
          offsetCenter: [0, '-20%'],
          fontSize: 12
        },
        detail: {
          fontSize: 30,
          offsetCenter: [0, '0%'],
          valueAnimation: true,
          formatter: function(value: number) {
            return value + '%'
          },
          color: 'auto'
        },
        data: [
          {
            value: 92
          }
        ]
      }
    ]
  }
  
  onTimeChartInstance.setOption(option)
}

// 初始化偏差图表
const initDeviationChart = () => {
  if (!deviationChart.value) return
  
  deviationChartInstance = echarts.init(deviationChart.value)
  
  const option = {
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      name: '天数',
      axisLabel: {
        formatter: '{value} 天'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 天'
    },
    series: [
      {
        data: [-1.2, -0.5, -0.9, -0.3, -1.5, -0.8],
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#409EFF'
        },
        lineStyle: {
          width: 3
        },
        markLine: {
          data: [
            { 
              type: 'average',
              name: '平均值',
              lineStyle: {
                color: '#E6A23C'
              }
            }
          ]
        }
      }
    ]
  }
  
  deviationChartInstance.setOption(option)
}

// 初始化生产周期图表
const initCycleChart = () => {
  if (!cycleChart.value) return
  
  cycleChartInstance = echarts.init(cycleChart.value)
  
  const option = {
    xAxis: {
      type: 'category',
      data: ['标准产品', '定制产品', '预制件']
    },
    yAxis: {
      type: 'value',
      name: '天数',
      axisLabel: {
        formatter: '{value} 天'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 天'
    },
    series: [
      {
        data: [10, 18, 8],
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
  
  cycleChartInstance.setOption(option)
}

// 窗口大小变化时重绘图表
const resizeCharts = () => {
  onTimeChartInstance?.resize()
  deviationChartInstance?.resize()
  cycleChartInstance?.resize()
}

// 组件挂载完成
onMounted(() => {
  // 初始化图表，使用setTimeout确保DOM已经渲染
  setTimeout(() => {
    initOnTimeChart()
    initDeviationChart()
    initCycleChart()
  }, 100)
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts)
})

// 组件卸载前清理
onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts)
  onTimeChartInstance?.dispose()
  deviationChartInstance?.dispose()
  cycleChartInstance?.dispose()
})
</script>

<style scoped>
.delivery-calculation-container {
  padding: 20px;
}

.delivery-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filters {
  margin-bottom: 20px;
}

.calendar-view {
  margin-bottom: 20px;
}

.inner-card {
  height: 100%;
}

.inner-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.calendar-container {
  position: relative;
}

.calendar-legend {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
}

.color-box {
  width: 15px;
  height: 15px;
  margin-right: 5px;
  border-radius: 3px;
}

.color-box.normal {
  background-color: #67C23A;
}

.color-box.medium {
  background-color: #E6A23C;
}

.color-box.high {
  background-color: #F56C6C;
}

.color-box.overload {
  background-color: #9932CC;
}

.calendar-cell {
  height: 100%;
  position: relative;
}

.normal-capacity {
  background-color: rgba(103, 194, 58, 0.1);
}

.medium-capacity {
  background-color: rgba(230, 162, 60, 0.1);
}

.high-capacity {
  background-color: rgba(245, 108, 108, 0.1);
}

.overload-capacity {
  background-color: rgba(153, 50, 204, 0.1);
}

.capacity-info {
  position: absolute;
  bottom: 2px;
  right: 2px;
  font-size: 12px;
  color: #606266;
}

.prediction-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.input-section {
  margin-bottom: 20px;
}

.result-section {
  flex-grow: 1;
}

.statistics-section {
  margin-top: 20px;
}

.stat-card {
  height: 200px;
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-chart {
  height: 120px;
}
</style> 